package com.mornd.storage.config;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * @author: mornd
 * @dateTime: 2023/8/1 - 22:46
 */

@Configuration
@EnableConfigurationProperties({MinioConfigProperties.class})
@ConditionalOnClass(MinioConfigProperties.class)
public class MinioAutoConfiguration {
    @Resource
    private MinioConfigProperties minioConfigProperties;

    @Bean
    public MinioClient buildMinioClient() {
        MinioClient minioClient = MinioClient.builder()
                .credentials(minioConfigProperties.getRootName(), minioConfigProperties.getRootPassword())
                .endpoint(minioConfigProperties.getEndpoint())
                .build();

        // bucket 不存在则创建，权限默认私有
        String bucketName = minioConfigProperties.getBucket();
        BucketExistsArgs args = BucketExistsArgs.builder().bucket(bucketName).build();
        try {
            if (!minioClient.bucketExists(args)) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return minioClient;
    }
}
